#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <queue>
#include "Task.hpp"

using namespace std;

static const int defaultNum = 5;

struct ThreadInfo//每个线程的信息
{
    pthread_t _tid;
    string _name;
};

template<class T>
class threadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&__add_grouping);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond,&_mutex);
    }
public:
    threadPool(int num = defaultNum)
        :_threads(num)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_cond,nullptr);
    }

    static void* HanderTask(void* args)
    {
        threadPool<T>* tp = static_cast<threadPool<T>*>(args);
        while(true)
        {
            tp.Lock();
            //
            while(tp->_tasks.empty())
            {
                tp->ThreadSleep();
            }
            T t = _tasks.front();
            _tasks.pop();//拿出任务
            tp->LockUnlock();
            t();//处理任务【仿函数()】

        }
    }
    void Start()//启动线程
    {
        int num = _threads.size();
        for(int i = 0; i < num; i++)
        {
            _threads[i]._name = "thread" + to_string(i + 1);
            pthread_create(&(_threads[i]._tid), nullptr, HanderTask, this);
            //传递this指针，可以让static成员函数访问到成员变量
        }
    }

    void Push(const T& in)//放任务
    {
        Lock();
        _tasks.push(in);
        Wakeup();
        Unlock(); 
    }
    void Pop()
    {
        T t = _tasks.front();
        _tasks.pop();//拿出任务
        
    }
    ~threadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
private:
    vector<ThreadInfo> _threads;
    queue<T> _tasks;

    pthread_mutex_t _mutex;//加锁
    pthread_cond_t _cond;//对线程唤醒
};